#!/usr/bin/python
# -*- coding: UTF-8 -*-

# GB28181协议相关

import hashlib
import requests
from typing import Any, Dict


class ObjectDict(Dict[str, Any]):

    def __getattr__(self, name: str) -> Any:
        try:
            return self[name]
        except KeyError:
            raise AttributeError(name)

    def __setattr__(self, name: str, value: Any) -> None:
        self[name] = value


class ApiHelper_LiveGBS(object):

    def __init__(self, host, username, password):
        self.host = host
        self.username = username
        self.password = password

    def check_result(self, response):
        if response.status_code == 200:
            params = ObjectDict(**(response.json()))
            return params
        raise ValueError("接口请求失败")

    @property
    def login_token(self):
        hl = hashlib.md5()
        # Tips
        # 此处必须声明encode
        # 若写法为hl.update(str) 报错为： Unicode-objects must be encoded before hashing
        hl.update(self.password.encode(encoding='utf-8'))
        data = {
            'username': self.username,
            'password': hl.hexdigest(),
        }
        result = requests.get("{}/api/v1/login".format(self.host), headers=data)
        return self.check_result(result)['Token']

    def get_channel_list_by_live_gbs(self):
        """
        通过liveGBS通道列表
        """
        url = f'{self.host}/api/v1/device/channellist'
        headers = {
            'Cookie': "token={}".format(self.login_token)
        }
        result = requests.get(url, headers=headers)
        return self.check_result(result)['ChannelList']

    def get_device_list_by_live_gbs(self):
        """
        第一步：通过liveGBS设备列表DeviceList
        """
        url = f'{self.host}/api/v1/device/list'
        headers = {
            'Cookie': f"token={self.login_token}"
        }
        result = requests.get(url, headers=headers)
        return self.check_result(result)['DeviceList']

    def live_broadcast(self):
        live_broadcast_list = []
        channel_list = self.get_channel_list_by_live_gbs()
        for channel in channel_list:
            code = channel['DeviceID']
            serial = channel['ID']
            url = f'{self.host}/api/v1/stream/start?serial={serial}&code={code}'
            headers = {
                'Cookie': f"token={self.login_token}"
            }
            result = requests.get(url, headers=headers)
            live_broadcast_list.append(self.check_result(result))
        return live_broadcast_list


# if __name__ == '__main__':
#     config = {
#         "host": "http://10.168.1.133:10000",
#         "username": "wtfc_user",
#         "password": "wtfcuser123456"
#     }
#     a = ApiHelper_LiveGBS(**config)
#     # print(a.login_token())
#
#     # print(a.get_device_list_by_live_gbs())
#     # print(a.get_channel_list_by_live_gbs())
#     print(a.live_broadcast())
